﻿using System;
using System.Collections.Generic;
using System.Linq;
using XRM.Security.DataAccess.Repositories.Impl;
using XRM.Security.WebUI.Helpers;

namespace XRM.Security.WebUI.Models.Report.ReportBuilder
{
    public class DepartmentByScsiReportBuilder : ReportBuilderBase
    {
        private readonly UserSkziRepository _repository;
        public DepartmentByScsiReportBuilder(UserSkziRepository repository)
        {
            _repository = repository;
        }

        public override string TemplateFileName
        {
            get { return "Учреждения, подключенные к защищенной среде"; }
        }

        public override string Create(CreateReportModel model)
        {
            var sksiKinds = model.GetSelectedCheckBoxValues().ToList();
            var query = _repository.GetAll( s => s.DeleteDate == null && sksiKinds.Contains( s.SkziKindId ) )
                .Where( s => s.UserRegister.DepartmentId != null )
                .Select( s => new { DepartmentName = s.UserRegister.Department.Name, SksiName = s.SkziKind.ShortName } )
                .OrderBy( s => s.DepartmentName ).ThenBy( s => s.SksiName );
            var departmentList = new List<DepartmentsReportTypeDepartment>();
            foreach ( var departmentGroup in query.GroupBy(s => s.DepartmentName))
            {
                foreach (var scsiGroup in departmentGroup.GroupBy(s => s.SksiName))
                {
                    departmentList.Add( new DepartmentsReportTypeDepartment
                    {
                            DepartmentName = departmentGroup.Key,
                            SCSIAmount = scsiGroup.Count().ToString(),
                            SCSIKind = scsiGroup.Key
                    });    
                }
            }
            var report = new DepartmentsReportType
                {
                    CreateDate = DateTime.Now,
                    Department = departmentList.ToArray()
                };
            return CreateXlsxDocument( Utils.SerializeToString( report ) );
        }
    }
}